package org.example.exp2.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.example.exp2.common.CommonResponse;
import org.example.exp2.common.ResponseCode;
import org.example.exp2.entity.Book;
import org.example.exp2.entity.BookVO;
import org.example.exp2.mapper.BookMapper;
import org.example.exp2.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wml
 * @since 2024-06-06 03:32:50
 */
@RestController
@RequestMapping("/books")
@Tag(name = "图书管理API")
public class BookController {
    @Autowired
    BookService bookService;
    @Autowired
    BookMapper bookMapper;
    @Value("${server.port}")
    private int serverPort;
    public String getUrl() {
        return "http://localhost:" + serverPort;
    }
    @GetMapping("")
    @Operation(summary = "获取图书列表", description = "根据关键词搜索图书")
    public CommonResponse<Map<String, Object>> getBooks(
            @Parameter(description = "页码")@RequestParam(defaultValue = "1") int pageNum,
            @Parameter(description = "每页数量")@RequestParam(defaultValue = "10") int pageSize,
            @Parameter(description = "书名关键词")String titleKeyword,
            @Parameter(description = "作者关键词")@RequestParam(required = false) String authorKeyword,
            @Parameter(description = "ISBN号")@RequestParam(required = false) String isbn,
            @Parameter(description = "是否可用")@RequestParam(required = false) Boolean available){
        IPage<Book> books = bookService.getBooks(pageNum, pageSize, titleKeyword, authorKeyword, isbn, available);
        // 设置每个Book的_links属性
        // 将Book对象转换为BookResource对象并添加链接
        List<BookVO> bookvo = books.getRecords().stream()
                .map(book -> {
                    BookVO resource = new BookVO(book.getBookId(), book.getTitle(), book.getAuthor(), book.getIsbn(), book.isAvailable());
                    resource.setLinks(getUrl());
                    return resource;
                })
                .collect(Collectors.toList());
        Map<String, Object> response = new HashMap<>();
        response.put("books", bookvo);
        response.put("total", books.getTotal());

        CommonResponse<Map<String, Object>> commonResponse = new CommonResponse<>(ResponseCode.SUCCESS.getCode(), "获取图书列表成功", response);
        commonResponse.getData().addLink("self", getUrl() + "/books");

        return commonResponse;
    }

    @GetMapping("/{bookId}")
    @Operation(summary = "获取单个图书信息", description = "根据图书ID获取详细信息")
    public CommonResponse<Book> getBook(@Parameter(description = "图书ID", required = true) @PathVariable("bookId") int bookId){
        Book book = bookMapper.selectById(bookId);

        CommonResponse<Book> commonResponse = new CommonResponse<>(ResponseCode.SUCCESS.getCode(), "获取图书详情成功", book);
        commonResponse.getData().addLink("self", getUrl() + "/books");

        return commonResponse;
    }

    @PostMapping("")
    @Operation(summary = "添加新图书", description = "新增一本图书到系统中")
    public CommonResponse<Map<String, Object>> addBook(@Parameter(description = "图书对象", required = true) @RequestBody Book book){
        int result = bookMapper.insert(book);
        if (result > 0) {
            Map<String, Object> response = new HashMap<>();
            response.put("bookId", book.getBookId());

            CommonResponse<Map<String, Object>> commonResponse = new CommonResponse<>(ResponseCode.SUCCESS.getCode(), "新图书添加成功", response);
            commonResponse.getData().addLink("self", getUrl() + "/books/" + book.getBookId());

            return commonResponse;
        } else {
            return new CommonResponse<>(ResponseCode.ERROR.getCode(), "新图书添加失败");
        }
    }

    @PutMapping("/{bookId}")
    @Operation(summary = "更新图书信息", description = "根据图书ID更新图书信息")
    public CommonResponse<Void> updateBook(@Parameter(description = "图书ID", required = true) @PathVariable("bookId") int bookId,
                                           @Parameter(description = "图书对象", required = true) @RequestBody Book book){
        book.setBookId(bookId);
        int result = bookMapper.updateById(book);
        if (result > 0) {
            CommonResponse<Void> commonResponse = new CommonResponse<>(ResponseCode.SUCCESS.getCode(), "图书信息更新成功");
            commonResponse.getData().addLink("self", getUrl() + "/books/" + book.getBookId());

            return commonResponse;
        } else {
            return new CommonResponse<>(ResponseCode.ERROR.getCode(), "图书信息更新失败");
        }
    }

    @DeleteMapping("/{bookId}")
    @Operation(summary = "删除图书", description = "根据图书ID从系统中删除图书")
    public CommonResponse<Void> deleteBook(@Parameter(description = "图书ID", required = true) @PathVariable("bookId") int bookId){
        int result = bookMapper.deleteById(bookId);
        if (result > 0) {
            CommonResponse<Void> commonResponse = new CommonResponse<>(ResponseCode.SUCCESS.getCode(), "图书删除成功");
            commonResponse.getData().addLink("self", getUrl() + "/books");

            return commonResponse;
        } else {
            return new CommonResponse<>(ResponseCode.ERROR.getCode(), "图书删除失败");
        }
    }
}